package org.springframework.social.showcase.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.social.UserIdSource;
import org.springframework.social.autoconfigure.SocialAutoConfigurerAdapter;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.google.api.Google;
import org.springframework.social.google.connect.GoogleConnectionFactory;
import org.springframework.social.showcase.user.SecurityContext;


/**
 * Created on 2018/1/12.
 *
 * @author zlf
 * @since 1.0
 */
@Configuration
public class GoogleAuthConfig extends SocialAutoConfigurerAdapter {

  @Value("${spring.social.google.app-id}")
  String appId;
  @Value("${spring.social.google.app-secret}")
  String secret;

  @Override
  protected ConnectionFactory<?> createConnectionFactory() {
    GoogleConnectionFactory googleConnectionFactory = new GoogleConnectionFactory(appId, secret);
    googleConnectionFactory.setScope("profile");
    return googleConnectionFactory;
  }

  @Override
  public UserIdSource getUserIdSource() {
    return () -> {
      String id;
      try {
        id = SecurityContext.getCurrentUser().getId();
      } catch (Exception e) {
        e.printStackTrace();
        id = SecurityContextHolder.getContext().getAuthentication().getName();
      }
      return id;
    };
  }

  @Bean
  @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
  public Google google(ConnectionRepository repository) {
    Connection<Google> connection = repository.findPrimaryConnection(Google.class);
    return connection != null ? connection.getApi() : null;
  }
}
